package com.yang.crawler.pdf.config;


import com.alibaba.fastjson.JSONObject;
import com.yang.crawler.thread.manager.ThreadPoolMonitorManager;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Component
public class PdfPropertyContext implements ApplicationListener<ApplicationEvent> {
    private ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();

    private PdfProperty pdfProperty;

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof ContextClosedEvent) {
            shutdown();
        }
    }

    private synchronized void shutdown() {
        try {
            scheduledExecutorService.shutdown();
            scheduledExecutorService.awaitTermination(ThreadPoolMonitorManager.SHUTDOWN_WAIT_TIME, ThreadPoolMonitorManager.SHUTDOWN_TIME_UNIT);
            if (!scheduledExecutorService.isTerminated()) {
                scheduledExecutorService.shutdownNow();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @PostConstruct
    public void init() {
        scheduledExecutorService.scheduleAtFixedRate(() -> {
            String path = this.getClass().getClassLoader().getResource("pdf-config.json").getPath();
            StringBuilder stringBuilder = new StringBuilder();
            try (FileInputStream inputStream = new FileInputStream(path)) {
                byte[] buffer = new byte[4 * 1024];
                int len = -1;
                while ((len = inputStream.read(buffer)) != -1) {
                    stringBuilder.append(new String(buffer, 0, len));
                }
                this.pdfProperty = JSONObject.parseObject(stringBuilder.toString(), PdfProperty.class);
                System.out.println(this.pdfProperty);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }, 0, 60, TimeUnit.SECONDS);
    }

    public PdfProperty getPdfProperty() {
        return this.pdfProperty;
    }

    public Float getTitleFontSize() {
        return this.pdfProperty.getTitleFontSize();
    }

    public Float getParagraphFontSize() {
        return this.pdfProperty.getParagraphFontSize();
    }

    public Float getHScale() {
        return this.pdfProperty.getHScale();
    }
}
